package com.iretailer.report.init;

import com.iretailer.report.init.annotation.BootLoading;
import com.iretailer.report.init.annotation.ExecutionMethod;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @Auther Bennie
 * @Date 2020/6/15 10:35
 * @Description
 */

@Component
@Slf4j
public class InitClass implements CommandLineRunner {
    private final ExecutorService threadPool;
    private final ApplicationContext applicationContext;

    public InitClass(ApplicationContext applicationContext, ExecutorService threadPool) {
        this.applicationContext = applicationContext;
        this.threadPool = threadPool;
    }

    @Override
    public void run(String... args) {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(BootLoading.class);
        beansWithAnnotation.forEach((key, value) -> {
            Method[] methods = value.getClass().getMethods();
            for (Method m : methods) {
                if (m.isAnnotationPresent(ExecutionMethod.class)) {
                    try {
                        m.invoke(value);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        });
    }
}
